// utils/utils.go
package utils

import (
	"path/filepath"
	"strings"
)

// SupportedPreviewExts 定义支持预览的文件扩展名
var SupportedPreviewExts = map[string]bool{
	// Text
	".txt": true, ".md": true, ".json": true, ".xml": true, ".csv": true, ".log": true,
	".go": true, ".py": true, ".js": true, ".ts": true, ".jsx": true, ".tsx": true,
	".html": true, ".htm": true, ".css": true, ".scss": true, ".less": true,
	".java": true, ".c": true, ".cpp": true, ".h": true, ".hpp": true, ".rs": true,
	".rb": true, ".php": true, ".sh": true, ".bat": true,
	".ini": true, ".conf": true, ".yaml": true, ".yml": true,
	// Images
	".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".bmp": true,
	".webp": true, ".svg": true, ".tiff": true, ".tif": true, ".ico": true,
	".heic": true, ".heif": true, ".avif": true,
	// Documents
	".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, ".ppt": true, ".pptx": true,
}

// SanitizeFilename prevents path traversal
func SanitizeFilename(name string) string {
	base := filepath.Base(name)
	if base == "." || base == ".." {
		return ""
	}
	return base
}

// IsPathInUploadDir checks if the file path is within the upload directory
func IsPathInUploadDir(filePath, uploadDir string) (bool, error) {
	absPath, err := filepath.Abs(filePath)
	if err != nil {
		return false, err
	}
	baseAbs, err := filepath.Abs(uploadDir)
	if err != nil {
		return false, err
	}
	return strings.HasPrefix(absPath, baseAbs), nil
}

// IsFileInUse checks if error is due to file being in use (Windows)
func IsFileInUse(err error) bool {
	if err == nil {
		return false
	}
	msg := err.Error()
	return strings.Contains(msg, "being used by another process") ||
		strings.Contains(msg, "access denied")
}
